package com.qf.filter;

import com.qf.leadnewsutils.commons.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Map;
import java.util.function.Consumer;

@Component
@Order(-5)
public class LoginFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //放行不需要过滤的资源（登录、注册）
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        URI uri = request.getURI();
        String path = uri.getPath();
        if (path.contains("/login/login_auth")){
            //放行
            return chain.filter(exchange);
        }

        //获取请求头-token
        String token = request.getHeaders().getFirst("token");
        if (token == null && token.length() == 0){
            //没有token，没有登录，停止路由
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //有token，对token进行验证
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);

        int i = AppJwtUtil.verifyToken(claimsBody);

        if (i == 1 || i == 2){
            //过期或者解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //可以将登录用户的id直接携带到目标服务中，目标服务中就不需要再次去解析jwt
        Integer id = (Integer) claimsBody.get("id");
        //将解析得到的id通过请求头转到目标服务
        ServerHttpRequest newReq = request.mutate().headers(httpHeaders -> {
            httpHeaders.add("uid",id+"");
        }).build();

        ServerWebExchange newExchange = exchange.mutate().request(newReq).build();

        //放行
        return chain.filter(newExchange);
    }
}
